<!--  -->
<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-row :gutter="10">
                <el-col :span="7">
                    <el-input v-model="queryInfo.query" placeholder="请输入用户名" class="input-with-select">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span='3'>
                    <el-dropdown>
                        <el-button type="primary">
                            筛选用户<i class="el-icon-arrow-down el-icon--right"></i>
                        </el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item @click.native="setqueryValue(null)">全部</el-dropdown-item>
                            <el-dropdown-item @click.native="setqueryValue(2)">黑名单用户</el-dropdown-item>
                            <el-dropdown-item @click.native="setqueryValue(1)">正常用户</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                </el-col>
                 <el-col :span="3">
                    <el-button type="primary" @click="addUser"><i class="el-icon-plus el-icon--left"></i>添加测试用户</el-button>
                </el-col>
            </el-row>
            <el-table :data="userlist" border stripe :header-cell-style="{'text-align':'center'}">
                <el-table-column label="序号" type="index" width="50px" align="center"></el-table-column>
                <el-table-column label="用户id" prop="userId" width="200px" align="center"></el-table-column>
                <el-table-column label="用户名" prop="userName" align="center" width="150px"></el-table-column>
                <el-table-column label="密码" prop="password" width="120px"></el-table-column>
                <el-table-column label="性别" prop="userSex" align="center">
                  <template slot-scope="scope">
                        <el-tag v-if="scope.row.userSex == '保密'" effect="plain" type="warning"  style="margin-right:4px; margin-bottom:4px">
                            保密
                        </el-tag>
                        <el-tag v-if="scope.row.userSex == '女'" effect="plain" type="danger"  style="margin-right:4px; margin-bottom:4px">
                            女生
                        </el-tag>
                        <el-tag v-if="scope.row.userSex == '男'" effect="plain" style="margin-right:4px; margin-bottom:4px">
                            男生
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="手机号" prop="phone" align="center" width="120px"></el-table-column>
                <el-table-column label="微信" prop="userWechat" align="center" width="120px"></el-table-column>
                <el-table-column label="邮箱" prop="userEmail" align="center" width="200px"></el-table-column>
                <el-table-column label="状态" prop="userState" width="100px" align="center" >
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.userState == 1" type="success" effect="dark" style="margin-right:4px; margin-bottom:4px">
                            正常
                        </el-tag>
                        <el-tag v-if="scope.row.userState == 2" type="info" effect="dark" style="margin-right:4px; margin-bottom:4px">
                            黑名单
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="学校" prop="userSchool" width="120px" align="center"></el-table-column>
                <el-table-column label="校区" prop="userAddress" align="center"></el-table-column>
                <!-- <el-table-column label="头像" prop="useravatar"></el-table-column> -->
                <el-table-column label="注册时间" prop="userRegisterTime" width="200px" align="center"></el-table-column>
                <el-table-column
                    fixed="right"
                    label="操作"
                    width="115" align="center">
                    <template slot-scope="scope">
                        <el-button @click="editClick(scope.row)" type="primary" icon="el-icon-edit" circle></el-button>
                        <el-button @click="deleteUserClick(scope.row)" type="danger" icon="el-icon-delete" circle></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pageNum"
                :page-sizes="[6, 10, 20, 30]"
                :page-size="queryInfo.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </el-card>

        <!-- 修改用户信息 -->
        <el-dialog
            title="修改用户信息"
            :visible.sync="editDialogVisible"
            width="40%">
            <el-form :model="editForm" :rules="editFromRules" status-icon  ref="editFormRef" label-width="100px" class="demo-ruleForm">
                <el-form-item label="用户名" prop="userName">
                    <el-input type="text" v-model="editForm.userName" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input type="text" v-model="editForm.phone" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type="text" v-model="editForm.password" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="性别">
                    <el-radio-group v-model="editForm.userSex" size="medium">
                    <el-radio border label="男"></el-radio>
                    <el-radio border label="女"></el-radio>
                    <el-radio border label="保密"></el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="学校" prop="userSchool">
                    <el-input type="text" v-model="editForm.userSchool" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="校区">
                  <el-select v-model="editForm.userAddress" placeholder="请选择校区">
                    <el-option label="广州" value="广州"></el-option>
                    <el-option label="三水" value="三水"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="邮箱" prop="userEmail">
                    <el-input type="text" v-model="editForm.userEmail" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="微信" prop="userWechat">
                    <el-input type="text" v-model="editForm.userWechat" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="用户状态">
                  <el-select v-model="editForm.userState" placeholder="请选择用户状态">
                    <el-option label="正常" value="1"></el-option>
                    <el-option label="黑名单" value="2"></el-option>
                  </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="updateUserInfo">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 添加测试用户 -->
        <el-dialog
            title="添加测试用户"
            :visible.sync="addDialogVisible"
            width="40%">
            <el-form :model="addForm" :rules="addFormRules" status-icon  ref="addFormRef" label-width="100px" class="demo-ruleForm">
                <el-form-item label="用户名" prop="userName">
                    <el-input type="text" v-model="addForm.userName" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                    <el-input type="text" v-model="addForm.phone" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type="text" v-model="addForm.password" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="性别">
                    <el-radio-group v-model="addForm.userSex" size="medium">
                    <el-radio border label="男"></el-radio>
                    <el-radio border label="女"></el-radio>
                    <el-radio border label="保密"></el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="学校" prop="userSchool">
                    <el-input type="text" v-model="addForm.userSchool" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="校区">
                  <el-select v-model="addForm.userAddress" placeholder="请选择校区">
                    <el-option label="广州" value="广州"></el-option>
                    <el-option label="三水" value="三水"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="邮箱" prop="userEmail">
                    <el-input type="text" v-model="addForm.userEmail" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="微信" prop="userWechat">
                    <el-input type="text" v-model="addForm.userWechat" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="用户状态">
                  <el-select v-model="addForm.userState" placeholder="请选择用户状态">
                    <el-option label="正常" value="1"></el-option>
                    <el-option label="黑名单" value="2"></el-option>
                  </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUserInfo">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>

// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';

export default {
// import引入的组件需要注入到对象中才能使用
  components: {},
  data () {
    // 手机号验证
    var checkPhone = (rule, value, callback) => {
      const phoneReg = /^1[3|4|5|6|7|8][0-9]{9}$/
      if (!value) {
        return callback(new Error('请输入手机号码'))
      }
      setTimeout(() => {
        if (!Number.isInteger(+value)) {
          callback(new Error('请输入数字值'))
        } else {
          if (phoneReg.test(value)) {
            callback()
          } else {
            callback(new Error('手机号码格式不正确'))
          }
        }
      }, 100)
    }
    // 这里存放数据
    return {
      queryInfo: {
        query: '',
        userState: null,
        pageNum: 1,
        pageSize: 6
      },
      userlist: [],
      total: 0,
      srcList: [],
      editDialogVisible: false,
      editForm: [],
      inputVisible: false,
      inputValue: '',
      editFromRules: {
        userName: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        phone: [
          { required: true, validator: checkPhone, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        userEmail: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['change'] }
        ]
      },
      addFormRules: {
        userName: [
          { required: true, message: '用户名不能为空', trigger: 'blur' }
        ],
        phone: [
          { required: true, validator: checkPhone, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' }
        ],
        userEmail: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['change'] }
        ]
      },
      addDialogVisible: false,
      addForm: {
        userName: '',
        phone: '',
        password: '',
        userSex: '保密',
        userSchool: '广东财经大学',
        userAddress: '',
        userWechat: '',
        userEmail: '',
        userRegisterTime: '2000-03-28',
        userState: ''
      }
    }
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 方法集合
  methods: {
    async getUserList () {
      const { data: res } = await this.$axios.get('admin/getalluser', { params: this.queryInfo })
      if (res.code !== 200) {
        return this.$message.error(res.msg)
      }
      this.userlist = res.data
      for (var i = 0; i < this.userlist.length; i++) {
        console.log(this.userlist[i].useravatar)
        this.srcList.push(this.userlist[i].useravatar)
      }
      this.total = res.count
    },
    handleSizeChange (newSize) {
      this.queryInfo.pageSize = newSize
      this.getUserList()
    },
    handleCurrentChange (newPage) {
      this.queryInfo.pageNum = newPage
      this.getUserList()
    },
    setqueryValue (value) {
      this.queryInfo.userState = value
      console.log(this.queryInfo.userState)
      this.getUserList()
    },
    editClick (scopeRow) {
      this.editDialogVisible = true
      this.editForm = scopeRow
      if (this.editForm.userState === 1) {
        this.editForm.userState = '正常'
      } else {
        this.editForm.userState = '黑名单'
      }
    },

    deleteUserClick (scopeRow) {
      this.$confirm('此操作将永久删除该用户, 并删除该用户在系统中的所有信息（包括发布、交易的各种记录等）, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete('admin/deleteuser/' + scopeRow.userId, {
          headers: {
            contentType: 'application/json;charset=UTF-8'
          }
        })
        if (res.code !== 200) {
          this.getUserList()
          return this.$message.error(res.msg)
        } else {
          this.getUserList()
          return this.$message.success(res.msg)
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },

    handleClose (tag) {
      this.editForm.usertab.splice(this.editForm.usertab.indexOf(tag), 1)
    },

    showInput () {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm () {
      const inputValue = this.inputValue
      if (inputValue) {
        this.editForm.usertab.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },

    changeDefaultAvatar () {
      if (this.editForm.usersex === '女') {
        this.editForm.useravatar = this.avatarwoman
      } else {
        this.editForm.useravatar = this.avatarman
      }
      this.$notify({
        title: '提示',
        message: '用户头像已置为' + this.editForm.usersex + '默认头像',
        duration: 1000
      })
    },

    updateUserInfo () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        this.editDialogVisible = false
        if (this.editForm.userState === '正常') {
          this.editForm.userState = 1
        } else {
          this.editForm.userState = 2
        }
        const { data: res } = await this.$axios.post('admin/updateuserinfo', this.editForm)
        if (res.code !== 200) {
          return this.$message.error(res.msg)
        } else {
          this.$message.success(res.msg)
        }
        this.getUserList()
      })
    },

    addUser () {
      this.addDialogVisible = true
    },
    addHandleClose (tag) {
      this.addForm.usertab.splice(this.addForm.usertab.indexOf(tag), 1)
    },

    addHandleInputConfirm () {
      const inputValue = this.inputValue
      if (inputValue) {
        this.addForm.usertab.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    addUserInfo () {
      console.log(this.addForm)
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        this.addDialogVisible = false
        const { data: res } = await this.$axios.post('admin/adduser', this.addForm)
        if (res.code !== 200) {
          return this.$message.error(res.msg)
        } else {
          this.$message.success(res.msg)
        }
        this.getUserList()
      })
    }
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created () {
    this.getUserList()
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted () {

  },
  beforeCreate () {}, // 生命周期 - 创建之前
  beforeMount () {}, // 生命周期 - 挂载之前
  beforeUpdate () {}, // 生命周期 - 更新之前
  updated () {}, // 生命周期 - 更新之后
  beforeDestroy () {}, // 生命周期 - 销毁之前
  destroyed () {}, // 生命周期 - 销毁完成
  activated () {} // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang='scss' scoped>

</style>
